package com.xuecheng.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;

/*
* 网关过滤器
* 1.交给容器管理
* 2.实现两个接口
* 3.实现两个方法
* 4.在filter中，完成校验处理
*
* */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /*过滤器的核心方法
     * exchange:请求上下文(获取request和response)
     * chain：过滤器链(向后执行)
     */
    @SneakyThrows
    @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.过滤不需要校验token的请求
        //2.1 获取请求的地址
        String path = request.getURI().getPath();
        //2.2 对于登录等等的地址，直接放行
        if(path.contains("coursePub/preview") ||
                path.contains("auth/login") ||
                path.contains("basic/dictionary") ||
                path.contains("category/tree-nodes")||
                path.contains("course/upload")||
                path.contains("search/")) {
            return chain.filter(exchange);
        }
        //3.获取请求头中的Authorization参数
        String token = request.getHeaders().getFirst("Authorization");
        //4.校验token，对于token异常的，返回401状态码
        Boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        //5.解析token(userId,companyId,companyName)
        Claims body = JwtUtils.parserToken(token).getBody();
        Long userId = body.get("userId", Long.class);
        Long companyId = body.get("companyId", Long.class);
        String companyName = body.get("companyName", String.class);
        //6.将用户信息，封装到java对象
        AuthInfo info = new AuthInfo();
        info.setUid(userId);
        info.setCompanyId(companyId);
        info.setCompanyName(companyName);
        //7.向下传递，到其他微服务,通过json传到请求头
        //搞了一个新的请求头
        String json = URLEncoder.encode(JSON.toJSONString(info), "UTF-8");
        ServerHttpRequest payload = request.mutate().headers(httpHeaders -> {
            httpHeaders.set("payload",json);
        }).build();
        //将请求头对象，添加到请求头中
        exchange.mutate().request(payload);
        return chain.filter(exchange);
    }

    //过滤器的优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
